package com.suxin.nio.test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author Tang
 * @classname Client
 * @description [  ]
 * @date 2021/2/1 21:22
 */
public class Client {

    public static void main(String[] args) throws Exception{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8888));
        while (!socketChannel.finishConnect()) {
            System.out.println("正在连接客户端!");
        }
        System.out.println("client ready ....");
        new Thread(() -> {
            try {
                read(socketChannel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        }
        socketChannel.close();
    }

    static void read(SocketChannel socketChannel) throws Exception {
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        while ((selector.select()) > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer allocate = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = channel.read(allocate)) != 0 && len != -1) {
                        allocate.limit(len - 1);
                        allocate.position(0);
                        System.out.println(" client server msg：--->" + new String(allocate.array()));
                        allocate.clear();
                    }
                }
                iterator.remove();
            }
        }
    }
}